# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : jwt封装类使用.py
# @Author: dongguangwen
# @Date  : 2024-06-22 12:46
from datetime import datetime, timedelta

import jwt


class JwtToken(object):

    _salt = "@^4_00wedv**pi)+(!w1rwi=d3q4l=ie=g-u$s8jevmj*zgg2h"

    _expire_message = dict(code=1200, msg="token 已经失效")

    _unknown_error_message = dict(code=4200, msg="token 解析失败")

    @classmethod
    def generate_token(cls, payload: dict) -> str:
        headers = dict(typ="jwt", alg="HS256")
        resut = jwt.encode(payload=payload, key=cls._salt, algorithm="HS256", headers=headers)
        return resut

    @classmethod
    def parse_token(cls, token: str) -> tuple:
        verify_status = False
        try:
            payload_data = jwt.decode(token, cls._salt, algorithms=['HS256'])
            verify_status = True
        except jwt.ExpiredSignatureError:
            payload_data = cls._expire_message
        except Exception as _err:
            payload_data = cls._unknown_error_message
        return verify_status, payload_data


if __name__ == '__main__':
    TEST_DATA = dict(name="mooor", exp=datetime.utcnow() - timedelta(seconds=1))
    token = JwtToken.generate_token(TEST_DATA)
    print(token)
    payload = JwtToken.parse_token(token)
    print(payload)

    TEST_DATA = dict(name="mooor", exp=datetime.utcnow() + timedelta(seconds=10))
    token = JwtToken.generate_token(TEST_DATA)
    print(token)
    payload = JwtToken.parse_token(token)
    print(payload)

    TEST_DATA = dict(name="mooor", exp=datetime.utcnow() + timedelta(seconds=10))
    token = JwtToken.generate_token(TEST_DATA)
    print(token)
    payload = JwtToken.parse_token(token + 'xxx')
    print(payload)


'''
eyJhbGciOiJIUzI1NiIsInR5cCI6Imp3dCJ9.eyJuYW1lIjoibW9vb3IiLCJleHAiOjE3MTkwMzE2ODh9.6Twf3kWc3YllBDPeZfB7AZmZKdcdyGDx6dUfsFydnvI
(False, {'code': 1200, 'msg': 'token 已经失效'})
eyJhbGciOiJIUzI1NiIsInR5cCI6Imp3dCJ9.eyJuYW1lIjoibW9vb3IiLCJleHAiOjE3MTkwMzE2OTl9.mQ_kAdUynZimw1PIUCzUIK9V9L10CxHYelsuH_JsoMI
(True, {'name': 'mooor', 'exp': 1719031699})
eyJhbGciOiJIUzI1NiIsInR5cCI6Imp3dCJ9.eyJuYW1lIjoibW9vb3IiLCJleHAiOjE3MTkwMzE2OTl9.mQ_kAdUynZimw1PIUCzUIK9V9L10CxHYelsuH_JsoMI
(False, {'code': 4200, 'msg': 'token 解析失败'})
'''